package utility.ftp.sftp;

import java.io.File;
import java.io.FileInputStream;
import java.util.Iterator;
import java.util.Vector;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

// http://kodehelp.com/java-program-for-uploading-file-to-sftp-server/
/**
 * @author kodehelp
 *
 */
public class SftpUpload {
	public SftpUpload() {
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		String SFTPHOST = "153.122.555.777";
		int SFTPPORT = 22;
		String SFTPUSER = "root";
		String SFTPPASS = "abcdbimat";// "abcd";
		// String SFTPWORKINGDIR = "/";
		String path = "/";
		String name = "admage.jp.key";

		Session session = null;
		Channel channel = null;
		ChannelSftp channelSftp = null;

		for (int i = 0; i < 1; i++) {
			try {
				JSch jsch = new JSch();
				session = jsch.getSession(SFTPUSER, SFTPHOST, SFTPPORT);
				session.setPassword(SFTPPASS);
				java.util.Properties config = new java.util.Properties();
				config.put("StrictHostKeyChecking",
						"" + System.currentTimeMillis());
				session.setConfig(config);
				session.connect();
				channel = session.openChannel("sftp");
				channel.connect();
				channelSftp = (ChannelSftp) channel;
				// channelSftp.cd(SFTPWORKINGDIR);
				File f = new File(path +name);
				System.out.println(System.currentTimeMillis());
				channelSftp
						.put(new FileInputStream(f), f.getName());
				System.out.println(System.currentTimeMillis());
				// channelSftp.put(FILETOTRANSFER, FILETOTRANSFER);

				channelSftp.pwd();
				System.out.println("cur dir: " + channelSftp.pwd());

				Vector<Object> v = channelSftp.ls(channelSftp.pwd());
				for (Iterator<Object> iterator = v.iterator(); iterator
						.hasNext();) {
					Object object = iterator.next();
					System.out.println("ls: " + object.toString());
				}

			} catch (Exception ex) {
				ex.printStackTrace();
				System.out.println("erroe: " + "upload");
			} finally {
				if (channelSftp != null) {
					channelSftp.disconnect();
				}
				if (session != null) {
					session.disconnect();
				}

			}
		}
	}
}
